// src/services/notificationService.ts
import PushNotification, {
  Importance,
  ReceivedNotification,
} from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
import { Platform } from 'react-native';
import api from './api';
import { navigationRef } from '../navigation/navigationUtils.ts';

interface NotificationData {
  title: string;
  message: string;
  data?: any;
  badge?: number;
  sound?: string;
  vibrate?: boolean;
}

class NotificationService {
  private isInitialized = false;

  // 初始化
  initialize(): void {
    if (this.isInitialized) return;

    PushNotification.configure({
      onRegister: (token) => {
        console.log('[Notification] Token:', token);
        this.registerDeviceToken(token.token);
      },

      onNotification: (notification) => {
        console.log('[Notification] Received:', notification);
        this.handleNotification(notification);

        // iOS需要调用finish
        if (Platform.OS === 'ios') {
          notification.finish(PushNotificationIOS.FetchResult.NoData);
        }
      },

      onAction: (notification) => {
        console.log('[Notification] Action:', notification.action);
        console.log('[Notification]:', notification);
      },

      onRegistrationError: (err) => {
        console.error('[Notification] Registration error:', err.message, err);
      },

      permissions: {
        alert: true,
        badge: true,
        sound: true,
      },

      popInitialNotification: true,
      requestPermissions: true,
    });

    // 创建默认通道（Android）
    if (Platform.OS === 'android') {
      PushNotification.createChannel(
        {
          channelId: 'default',
          channelName: 'Default Channel',
          channelDescription: 'Default notification channel',
          importance: Importance.HIGH,
          vibrate: true,
        },
        (created) => console.log('[Notification] Channel created:', created)
      );
    }

    this.isInitialized = true;
  }

  // 请求权限
  async requestPermissions(): Promise<boolean> {
    return new Promise((resolve) => {
      PushNotification.requestPermissions().then((permissions) => {
        // 使用 !! 确保结果是布尔值
        resolve(!!(permissions.alert || permissions.badge || permissions.sound));
      });
    });
  }

  // 注册设备token
  private async registerDeviceToken(token: string): Promise<void> {
    try {
      await api.post('/api/notification/register', {
        token,
        platform: Platform.OS,
      });
    } catch (error) {
      console.error('[Notification] Register token error:', error);
    }
  }

  // 处理通知
  private handleNotification(notification: Omit<ReceivedNotification, 'userInfo'>): void {
    // 根据通知类型处理
    const { data } = notification;

    if (data?.type === 'chat') {
      // 处理聊天通知
      this.handleChatNotification(data);
    } else if (data?.type === 'subscription') {
      // 处理订阅通知
      this.handleSubscriptionNotification(data);
    }
  }

  private handleChatNotification(data: any): void {
    // 导航到聊天页面
    navigationRef.navigate('Chat', { conversationId: data.conversationId } as any);
  }

  private handleSubscriptionNotification(data: any): void {
    // 导航到订阅页面
    navigationRef.navigate('Subscription');
  }

  // 显示本地通知
  showLocalNotification(data: NotificationData): void {
    PushNotification.localNotification({
      title: data.title,
      message: data.message,
      userInfo: data.data,
      number: data.badge, // <-- 正确属性
      soundName: data.sound || 'default',
      vibrate: data.vibrate !== false,
      channelId: 'default',
    });
  }

  // 显示定时通知
  scheduleNotification(data: NotificationData & { date: Date }): void {
    PushNotification.localNotificationSchedule({
      title: data.title,
      message: data.message,
      date: data.date,
      userInfo: data.data,
      soundName: data.sound || 'default',
      vibrate: data.vibrate !== false,
      channelId: 'default',
    });
  }

  // 取消所有通知
  cancelAllNotifications(): void {
    PushNotification.cancelAllLocalNotifications();
  }

  // 获取应用角标数
  getApplicationIconBadgeNumber(callback: (count: number) => void): void {
    PushNotification.getApplicationIconBadgeNumber(callback);
  }

  // 设置应用角标数
  setApplicationIconBadgeNumber(count: number): void {
    PushNotification.setApplicationIconBadgeNumber(count);
  }

  // 清除角标
  clearBadge(): void {
    this.setApplicationIconBadgeNumber(0);
  }

  // 获取已送达的通知
  getDeliveredNotifications(callback: (notifications: any[]) => void): void {
    PushNotification.getDeliveredNotifications(callback);
  }

  // 移除已送达的通知
  removeDeliveredNotifications(identifiers: string[]): void {
    PushNotification.removeDeliveredNotifications(identifiers);
  }

  // 移除所有已送达的通知
  removeAllDeliveredNotifications(): void {
    PushNotification.removeAllDeliveredNotifications();
  }
}

export default new NotificationService();